//
//  TSRechargeInfoViewController.swift
//  TSProfitProject
//
//  Created by TMS on 2019/11/6.
//  Copyright © 2019 TMS. All rights reserved.
//

import UIKit
import HandyJSON

protocol TSRechargeInfoViewControllerDelegate : NSObjectProtocol {
    func completeRecharge()
}

class TSRechargeInfoViewController: TSBaseViewController {
    
    weak var delegate : TSRechargeInfoViewControllerDelegate? = nil
    var tableView : UITableView!
    var model : TSRechargeModel? = nil
    
    lazy var footerView : UIView = {
        let footer = UIView.init(frame: CGRect(x: 0, y: 0, width: Int(SCREEN_WIDTH), height: 30+48+30))
        footer.backgroundColor = WHITE_COLOR
        
        let commitBtn = UIButton.init(type: .system)
        commitBtn.setTitle("提交", for: .normal)
        commitBtn.setTitleColor(WHITE_COLOR, for: .normal)
        commitBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        commitBtn.backgroundColor = BASE_RED_COLOR
        commitBtn.layer.cornerRadius = 24
        commitBtn.layer.masksToBounds = true
        commitBtn.addTarget(self, action: #selector(commitAction), for: .touchUpInside)
        footer.addSubview(commitBtn)
        commitBtn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(30)
            make.size.equalTo(CGSize(width: SCREEN_WIDTH*0.682, height: 48))
        }
        
        return footer
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupNavigationTitle(title: "充值")
        configViews()
        requestDatas()
    }
    
    @objc func commitAction() {
        IQKeyboardManager.shared().resignFirstResponder()
        NotificationCenter.default.post(name: .TSRechargeCommitNotification, object: nil)
    }

}

// MARK: - TSRechargeConfirmInfoTableViewCellDelegate
extension TSRechargeInfoViewController : TSRechargeConfirmInfoTableViewCellDelegate {
    
    func fitToCommit(usdt: String, name: String) {
        commitRecharge(money: usdt, ustdname: name)
    }
}

//MARK: - UITableViewDelegate
extension TSRechargeInfoViewController : UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        if section == 0 {

            let header = UIView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 44))
            header.backgroundColor = UIColor.hexadecimalColor(hexadecimal: "#F5F5F5")
            
            let titleLabel = UILabel.init()
            titleLabel.attributedText = setupSectionHeaderContent(section: section)
            header.addSubview(titleLabel)
            titleLabel.snp.makeConstraints { (make) in
                make.centerY.equalToSuperview()
                make.left.equalTo(12)
            }
            
            return header
            
        } else {
            
            let sectionView = UIView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 44))
            sectionView.backgroundColor = WHITE_COLOR
            
            let icon = UIView.init()
            icon.backgroundColor = BASE_RED_COLOR
            sectionView.addSubview(icon)
            icon.snp.makeConstraints { (make) in
                make.left.equalTo(15)
                make.bottom.equalTo(-15)
                make.size.equalTo(CGSize(width: 2, height: 13))
            }
            
            let label = UILabel.init()
            label.textColor = UIColor.hexadecimalColor(hexadecimal: "#454545")
            label.font = UIFont.systemFont(ofSize: 14)
            switch section {
            case 1:
                label.text = "充值步骤："
            case 2:
                label.text = "重要提示："
            default:break
            }
            sectionView.addSubview(label)
            label.snp.makeConstraints { (make) in
                make.centerY.equalTo(icon)
                make.left.equalTo(icon.snp.right).offset(7)
            }
            
            return sectionView
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        44
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 0.001))
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
}

//MARK: - UITableViewDataSource
extension TSRechargeInfoViewController : UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        
        var cell : UITableViewCell?
        
        if indexPath.section == 0 {
            var infoCell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(TSRechargeInfoTableViewCell.self)) as? TSRechargeInfoTableViewCell
            
            if infoCell == nil {
                infoCell = TSRechargeInfoTableViewCell.init(style: .default, reuseIdentifier: NSStringFromClass(TSRechargeInfoTableViewCell.self))
            }
            
            if self.model != nil {
                infoCell?.setupCell(model: self.model!)
            }
            
            cell = infoCell
            
        } else {

            var autoHeightCell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(TSAutoHeightTableViewCell.self)) as? TSAutoHeightTableViewCell
                
            if autoHeightCell == nil {
                autoHeightCell = TSAutoHeightTableViewCell.init(style: .default, reuseIdentifier: NSStringFromClass(TSAutoHeightTableViewCell.self))
            }
                
            autoHeightCell?.setupLabel(content: getInfoContent(section: indexPath.section), topInset: 0, textColor: "#A5A5A5", fontSize: 13)
            
            cell = autoHeightCell
            
        }
        
        return cell!
    }
}

//MARK: - Network Request
extension TSRechargeInfoViewController {
    
    // 获取汇率相关信息
    func requestDatas() {
        
        TSNetworkManager.request(TMSNetworkTools.rechargeUsdt, showHUD: true, success: { (data) in
            
            CBToast.hiddenToastAction()
            let responseDic = data as? NSDictionary
            let model = TSRechargeModel.deserialize(from: responseDic)
            self.model = model
            self.tableView.reloadData()
            
        }) { (error) in
            CBToast.hiddenToastAction()
        }
    }
    
    // 充值
    func commitRecharge(money:String, ustdname:String) {
        
        CBToast.showToastAction()
        TSNetworkManager.request(TMSNetworkTools.requestForRecharge(money: money, ustdname: ustdname), showHUD: true, success: { (data) in
            
            CBToast.showToastAction(message: "提交成功，等待审核")
            self.requestUserInfo()
            
        }) { (error) in
            
            CBToast.hiddenToastAction()
        }
    }
    
    // 刷新个人信息
    func requestUserInfo() {
        
        TSNetworkManager.request(TMSNetworkTools.getUserInfo, showHUD: false, success: { (data) in
            
            CBToast.hiddenToastAction()
            
            let responseDic = data as? NSDictionary
            var model = TSLoginModel.deserialize(from: responseDic)!
            model.token = TSLoginManager.shared.token
            model.user_id = TSLoginManager.shared.user_id
            TSLoginManager.shared.setUserModel(model: model)
            
            CBToast.showToastAction(message: "充值成功")
            self.tableView.reloadData()
            
            if self.delegate != nil {
                self.delegate?.completeRecharge()
            }
            
        }) { (error) in
            CBToast.hiddenToastAction()
        }
    }
}

//MARK: - Initialize
extension TSRechargeInfoViewController {
    
    func configViews() {
        
        tableView = UITableView.init(frame: .zero, style: .grouped)
        tableView.backgroundColor = WHITE_COLOR
        tableView.delegate = self;
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.tableFooterView = footerView
        tableView.estimatedRowHeight = 100
        tableView.rowHeight = UITableView.automaticDimension
        self.view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(T_NAVBARHEIGHT)
        }
        
        if #available(iOS 11, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
    }
    
    func getInfoContent(section : Int) -> String {
        
        switch section {
        case 1:
            return "1.在数字货币网购买USDT。\n2.数字货币交易网点击USDT提币、复制粘贴大潤發USDT充值地址、输入提币数量、确定。\n3.大潤發充值根据USDT区块网络速度自动到账中心钱包（折合RMB显示）。\n4.在数字货币网提现时，如有供选择方式，必须选择ERC-20提现。"
        
        case 2:
            return "大潤發平台充值地址会不定期更新，请每次充值务必核对最新的二维码钱包地址。r如因个人错误操作造成的损失，平台概不负责！"
        default:
            return ""
        }
    }
    
    func setupSectionHeaderContent(section:Int) -> NSAttributedString {
        
        let attributed : NSMutableAttributedString!
        
        let str = "收款信息"
        attributed = NSMutableAttributedString.init(string: str)
        attributed.addAttributes([NSAttributedString.Key.foregroundColor:BASE_GRAY_COLOR, NSAttributedString.Key.font:UIFont.systemFont(ofSize: 16, weight: .medium)], range: NSMakeRange(0, str.count))
        
        return attributed.copy() as! NSAttributedString
    }
}
